<?php
namespace app\push\controller;
use GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;
use app\push\model\DashboardV2;
use think\Session;
use think\Db;
/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Event
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id) {
        /* var_dump(DashboardV1::cpuPercent()); */
        //初始化数据并轮询推送基础数据
        $filePath = __DIR__."/../swp/noninit.txt";
        if(file_exists($filePath)){
            Db::name('admin')->where('id','gt',0)->update(['isonline'=>0]);
            unlink($filePath);
            $_SESSION['test'] = Timer::add(1,function() {
                $data = Db::name('swp')->select();
                Db::name('swp')->where('id','gt',0)->delete();
                if($data){
                    foreach($data as $v) {
                        switch($v['type']) {
                        case "DashboardV2":Gateway::joinGroup($v['client_id'],"DashboardV2");
                            $newMemberToDashboardV2[] = $v['client_id'];
                            break;
                        }
                    }
                }
                $newMemberToDashboardV2 = isset($newMemberToDashboardV2)?$newMemberToDashboardV2:null;
                self::DashboardV2($newMemberToDashboardV2);  
            });

        }
    }
    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message) {
        $arr = json_decode($message,true);
        switch ($arr['type']){
        case 'clientId':
            $_SESSION['group'] = $arr['group'];
            Gateway::sendToClient($client_id,json_encode(['type'=>'clientId','clientId'=>$client_id]));
            break;
        }
        // 向所有人发送 
        /* Gateway::sendToAll("$client_id said $message"); */
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id) {
        //如果当前帐号的所有连接都断开，数据库登录下线
        $group = $_SESSION['group'];
        $admin_id = $_SESSION['group'];
        $num = Gateway::getClientCountByGroup($group);
        var_dump($num);
        if($num == 0){
            Db::name('admin')->where('id','eq',$admin_id)->update(['isonline'=>0]);
        }
        /* dump(Gateway::getClientSessionsByGroup($_SESSION['admin_id'])); */
        // 向所有人发送 
        /* GateWay::sendToAll("$client_id logout"); */
    }


    /*---------------------------------------------------------
     *管理员后台:基础数据推送
     *思想:将每个后台的页面看作是一个组。管理员每打开一个页面，
     *将产生连接的id发到后台，跟对应的页面组进行邦定，并调用对
     *数应方法向组推送据
     *--------------------------------------------------------*/
    /*&*
     *每个帐号的id是个组，每帐号的连接加入这个组,用于判断，当前一个连接断开时，这个帐号还有没有其它连接，没有就判定帐号下线
     *
     *
     */
    public static function addGroup($arr) {
        $_SESSION['admin_id'] = $arr['admin_id'];
        $group = $arr['admin_id']; 
        $client_id = $arr['client_id'];
        Gateway::joinGroup($client_id,$group);
    }
    /*
     *推送DashboardV2页面数据
     *
     */
    public static function DashboardV2($newMember = null) {
        $group = "DashboardV2";
        $member =  Gateway::getClientCountByGroup($group);
        if($member > 0) {
            //cpu使用率
            preg_match_all('/[0-9]+\.[0-9]/',exec("top -n 2 -d 0.5| grep 'Cpu'"),$cpuArr);
            $cpuId = $cpuArr[0][3];
            $cpuPercent = 100 - $cpuId;
            $_SESSION['cpuPercent'] = empty($_SESSION['cpuPercent'])?null:$_SESSION['cpuPercent'];
            if($_SESSION['cpuPercent'] != $cpuPercent) {
                $data['cpuPercent'] = round($cpuPercent,2);
            }
            $_SESSION['cpuPercent'] = $cpuPercent;
            //内存使用
            exec('free -h',$commandArr);
            preg_match_all('/[0-9]{1,}/',$commandArr[1],$arr);
            $total_memory = $arr[0][0];
            $free_memory  = $arr[0][2];
            $_SESSION['free_memory'] = empty($_SESSION['free_memory'])?null:$_SESSION['free_memory'];
            if($_SESSION['free_memory'] != $free_memory){
                $data['free_memory'] = $free_memory;
                $data['total_memory'] = $total_memory;
            }
            $_SESSION['free_memory'] = $free_memory;

            //在线人数
            $allCount = Gateway::getAllClientCount();
            $_SESSION['allCount'] = empty($_SESSION['allCount'])?null:$_SESSION['allCount'];
            if($_SESSION['allCount'] != $allCount) {
                $data['allCount'] = $allCount;
            }
            $_SESSION['allCount'] = $allCount;

            //网络上下行
            exec('sar  -n DEV 1 1| grep ens33',$comandArr); 
            preg_match_all('/[0-9]{1,}\.[0-9]{1,}/',$comandArr[1],$arr);
            $rxpck = $arr[0][2];
            $txpck = $arr[0][3];
            $_SESSION['rxpck'] = empty($_SESSION['rxpck'])?null:$_SESSION['rxpck'];
            if($_SESSION['rxpck'] != $rxpck){
                $data['rxpck'] = $rxpck;
            }
            $_SESSION['rxpck'] = $rxpck;
            $_SESSION['txpck'] = empty($_SESSION['txpck'])?null:$_SESSION['txpck'];
            if($_SESSION['txpck'] != $txpck) {
                $data['txpck'] = $txpck;
            }
            $_SESSION['txpck'] = $txpck;
            //为新组员推送一次全部数据
            if($newMember){
                $tmpGroup = 'tmpGroup';
                foreach($newMember as $client_id){
                    Gateway::joinGroup($client_id,$tmpGroup);
                }
                $firstPush['cpuPercent'] = $cpuPercent; //cpu使用率
                $firstPush['free_memory']  = $free_memory;//空闲内存
                $firstPush['total_memory'] = $total_memory;//内存容量
                $firstPush['allCount']  = $allCount;//当前总连接
                $firstPush['rxpck'] = $rxpck;//下行
                $firstPush['txpck'] = $txpck;//上行
                $firstPush['type'] = 'DashboardV2';//当前页面
                Gateway::sendToGroup($tmpGroup,json_encode($firstPush));
                foreach($newMember as $client_id){
                    Gateway::leaveGroup($client_id,$tmpGroup);
                }
            }
            if(!empty($data)) {
                $data['type'] = "DashboardV2";
                Gateway::sendToGroup($group,json_encode($data));
                /* dump(Gateway::getClientSessionsByGroup($group)); */
            }
        }
    }
    /**
     *多个连接同一帐号加入admin_id的组
     *
     */
    public static function joinGroup($arr){
        $group = $arr['admin_id'];
        $clien_id = $arr['client_id'];
    }
}
